/**
 * 
 */
package com.wskj.library.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.code.kaptcha.Constants;
import com.wskj.library.pojo.UserInfo;
import com.wskj.library.service.UserService;
import com.wskj.library.service.impl.UserServiceImpl;

/**
 * @author 胡洋
 * @describe  前台登录的页面 
 * @Date 2018年3月22日下午5:43:24
 * @version 1.0
 */
@WebServlet(urlPatterns="/login.do")
public class LoginServlet extends HttpServlet {
	UserService userService=new UserServiceImpl();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {	
		//登录的时候 判断cookie 中是否有 uid 的字符串  
		Cookie[] cookies = req.getCookies();
		int uid=0;
		for(Cookie c:cookies) {
			if(c.getName().equals("uid")) {
				uid=Integer.parseInt(c.getValue());
				break;
			}
		}	
		if(uid>0) {
			//查询出cookie 中用户的信息 
			UserInfo user=userService.getUserById(uid);
			if(user!=null) {
				req.getSession().setAttribute("user",user);
				req.setAttribute("uname", user.getUname());
				req.setAttribute("upass",user.getPass());
			}
		}
		req.getRequestDispatcher("/WEB-INF/page/login.jsp").forward(req, resp);
	}
	
	
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//做用户权限的判断 ....		
		String name = req.getParameter("uname");
		String pass = req.getParameter("upass");
		String yanzhenma = req.getParameter("yanzhenma");
		String save = req.getParameter("save"); //是否保存 一周的时间 
		String sy =(String) req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		//检验验证码是否正确		
		if(sy.equalsIgnoreCase(yanzhenma)) {
		    UserInfo  user=userService.checkLogin(name,pass);
			//判断是否登录成功 ......
		    if(user!=null) {
		    	 req.getSession().setAttribute("user",user);		    					 
				 //判断是否需要保存 ...需要保存就返回一个秘钥  可以直接登录成功.....
				 if("1".equalsIgnoreCase(save)) {
					 Cookie cookie=new Cookie("uid",user.getUid()+""); 
					 cookie.setMaxAge(7*24*60*60*1000);
					 resp.addCookie(cookie);
				 }				 
				 resp.sendRedirect(req.getContextPath()+"/index.do");
				 return;
		    }
		}		
		resp.sendRedirect(req.getContextPath()+"/login.do");		
	}

}
